package framework.async
{
	import framework.remote.RemoteCollection;

	import mx.rpc.AbstractOperation;
	import mx.rpc.AsyncToken;

	public function chainInternal(responder:ChainResponder):void
	{
		var chain:Array = responder.chain;

		var func:Object = chain[0];
		var params:Array = chain[1] as Array;
		chain.splice(0, 2);

		var aToken:AsyncToken;
		if (func is AbstractOperation)
		{
			aToken = func.send.apply(this, params) as AsyncToken;
		}
		else if (func is Function)
		{
			var r:Object = func.apply(this, params);
			if (r is AsyncToken)
			{
				aToken = AsyncToken(r);
			}
			else if (r is RemoteCollection)
			{
				aToken = RemoteCollection(r).token;
			}
			else
			{
				throw new Error("Unsupported return value (not AsyncToken or RemoteCollection)");
			}
		}
		else
		{
			throw new Error("Unsupported operation. Only Function or AbstractOperation are supported");
		}
		if (aToken)
		{
			aToken.addResponder(responder);
		}
		else
		{
			if (chain.length)
				chainInternal(responder);
		}
	}
}